#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "views/clientstableview.h"
#include "dialogs/aboutdialog.h"
#include "views/clientsview.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    QIcon myIcon(":/icarus/gymIcon.png");
    QMainWindow::setWindowIcon(myIcon);
    ui->setupUi(this);
    currentMainWidget = NULL;
    connect(ui->shalala,SIGNAL(triggered()),this,SLOT(shalalaClicked()));
    connect(ui->tomala,SIGNAL(triggered()),this,SLOT(tomalaClicked()));
    connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(aboutClicked()));

}

MainWindow::~MainWindow()
{
    delete ui;

}

void MainWindow::timerEvent(QTimerEvent*) {
    IplImage *image=cvQueryFrame(camera);
    cvwidget->putImage(image);
}

void MainWindow::shalalaClicked(){

    removeCurrentWidget();

    CvCapture * camera = cvCreateCameraCapture(0);

    assert(camera);
    IplImage * image=cvQueryFrame(camera);
    assert(image);

    printf("Image depth=%i\n", image->depth);
    printf("Image nChannels=%i\n", image->nChannels);

    CameraWindow *mainWin = new CameraWindow(camera,this);

    currentMainWidget = mainWin;

    ui->gridLayout->addWidget(currentMainWidget);

    connect(mainWin, SIGNAL(error(QString)), this, SLOT(captureError(QString)));


    qDebug("shalala clicked!");
}

void MainWindow::aboutClicked(){

    AboutDialog *dialog = new AboutDialog(this);

    dialog->show();

}

void MainWindow::tomalaClicked(){
    qDebug("tomala clicked!");

    removeCurrentWidget();

    ClientsTableView *mainWin = new ClientsTableView(this);

    currentMainWidget = mainWin;

    ui->gridLayout->addWidget(currentMainWidget);
    connect(mainWin, SIGNAL(editClient(int)), this, SLOT(showClientEdit(int)));

}

void MainWindow::captureError( const QString& text ){
    QMessageBox::critical(this,windowTitle(), text);
}

void MainWindow::showClientEdit(int clientId){

    qDebug("editing client %d",clientId);

    removeCurrentWidget();

    ClientsView *mainwin = new ClientsView(clientId,this);
    currentMainWidget = mainwin;
    ui->gridLayout->addWidget(currentMainWidget);

}

void MainWindow::removeCurrentWidget(){

    if(currentMainWidget != NULL ){
        ui->gridLayout->removeWidget(currentMainWidget);
        delete currentMainWidget;
        qDebug("removed?!");
        currentMainWidget = NULL;
    }

}
